<?php

namespace App\Http\Controllers;

use App\Handlers\ImageUploadHandler;
use App\Models\Tag;
use App\Models\Topic;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\TopicRequest;
use Illuminate\Support\Arr;

class TopicsController extends Controller
{
    public function __construct()
    {

        $this->middleware('auth', ['except' => ['index', 'show']]);
    }

    public function index(Request $request)
    {

        $topics = $this->queryTopics();

        return view('topics.index', compact('topics'));
    }

    public function show(Request $request, Topic $topic)
    {
        $this->authorize('show', $topic);
        // URL 矫正
        if (!empty($topic->slug) && $topic->slug != $request->slug) {

            return redirect($topic->link(), 301);
        }

        // 更新流量
        if ($topic->publish) {
            $topic->increment('view_count', 1);
            /*$topic->view_count += 1;
            $topic->save();*/
        }

        return view('topics.show', compact('topic'));
    }

    public function create(Topic $topic)
    {
        $topic->category_id = intval(\request('category_id'));

        return view('topics.create_and_edit', compact('topic'));
    }

    public function store(TopicRequest $request, Topic $topic)
    {
        $topic->fill($request->all());
        $topic->user_id = $request->user()->id;

        $topic->save();

        $topic->tags()->sync($request->input('tags'));

        // 更新标签数量
        $topic->tags->map(function (Tag $tag) {

            return $tag->updateTopicCount();
        });

        return redirect()->to($topic->link())->with('success', '帖子创建成功！');

    }

    public function edit(Topic $topic)
    {
        $this->authorize('update', $topic);
        return view('topics.create_and_edit', compact('topic'));
    }

    public function update(TopicRequest $request, Topic $topic)
    {
        $this->authorize('update', $topic);
        $topic->update($request->all());
        $tags = $topic->tags;
        $ids = $request->input('tags');
        $topic->tags()->sync($ids);
        $items = [];
        foreach ($tags as $tag) {
            $items[$tag->id] = $tag;
        }
        foreach ($topic->tags as $tag) {
            $items[$tag->id] = $tag;
        }
        // 更新标签数量
        foreach ($items as $tag) {

            $tag->updateTopicCount();
        }

        return redirect()->to($topic->link())->with('success', '更新成功！');
    }

    public function destroy(Topic $topic)
    {
        $this->authorize('destroy', $topic);
        $topic->delete();

        return redirect()->route('topics.index')->with('success', '成功删除！');
    }

    public function uploadImage(Request $request, ImageUploadHandler $uploader)
    {
//json
//{
//    success : 0 | 1,           // 0 表示上传失败，1 表示上传成功
//    message : "提示的信息，上传成功或上传失败及错误信息等。",
//    url     : "图片地址"        // 上传成功时才返回
//}
        // 初始化返回数据，默认是失败的
        $data = [
            'success' => 0,
            'message' => '上传失败!',
            'url' => ''
        ];

        // 判断是否有上传文件，并赋值给 $file
        if ($file = $request->file('editormd-image-file')) {
            // 保存图片到本地
            $result = $uploader->save($file, 'topics', $request->user()->id, 1024);
            // 图片保存成功的话
            if ($result) {
                $data['url'] = $result['path'];
                $data['message'] = "上传成功!";
                $data['success'] = 1;
            }
        }
        return $data;
    }

    public function search(Request $request)
    {
        $keywords = $request->query('keywords');
        $keywords = purifier_search_keywords($keywords);

        $topics = $this->queryTopics(function ($query) use ($keywords) {
            $query->where('title', 'like', '%' . $keywords . '%')
                ->orWhere('excerpt', 'like', '%' . $keywords . '%');
        });

        return view('topics.index', compact('topics', 'keywords'));
    }

    protected function queryTopics($queryWhere = null)
    {

        return Topic::with('user', 'category', 'tags')
            ->where('publish', true)
            ->where($queryWhere)
            ->withOrder(request('order'))
            ->paginate(20);
    }
}
